﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using dotNetMembership = System.Web.Security.Membership;
using dotNetRoles = System.Web.Security.Roles;
using Binding = System.Web.Mvc.BindingHelperExtensions;
using StarterKits.Mvc.Filters.FormsAuthentication;
using StarterKits.Mvc.Membership.Controllers;
using P.InOut.NetMvc.Models;
using P.InOut.NetMvc.Properties;

namespace P.InOut.NetMvc.Controllers
{
    public class JsonProfiles
    {
        public int Status { get; set; }

        public long Queried { get; set; }

        public object Profiles { get; set; }
    }
    public class ProfilesServiceController : Controller
    {
        [RequiresAuthentication()]
        public JsonResult Get()
        {
            string partialTime = this.Request.Params["lastStatus"];
            long lastRequest = long.Parse(partialTime);

            // Get User
            MembershipUser user = Membership.GetUser(this.User.Identity.Name);

            // Open Data Context
            InOutDataContext db = new InOutDataContext(Settings.Default.dbConn);

            // Get list of teams user is a member of
            List<Team> memberOf = (from t in db.MemberTeams
                                   where t.UserId == (Guid)user.ProviderUserKey
                                   select t.Team).ToList<Team>();

            List<Guid> teamMembers = (from t in db.MemberTeams
                                      where memberOf.Contains(t.Team)
                                      select t.UserId).ToList<Guid>();

            var profileUpdates = (from p in db.Profiles
                                  where teamMembers.Contains(p.UserId) && p.TicksLastUpdated > lastRequest
                                  select new
                                  {
                                      UserId = p.UserId,
                                      DateTimeLastUpdated = p.DateTimeLastUpdated,
                                      UserName = HttpUtility.HtmlEncode(p.Aspnet_Membership.Aspnet_User.UserName),
                                      Status = HttpUtility.HtmlEncode(p.Status),
                                      InStatus = p.InStatus,
                                      OfficeStatus = p.OfficeStatus,
                                      OfficePhone = p.OfficePhone,
                                      RemotePhone = p.RemotePhone
                                  });

            JsonProfiles jsonStatus = new JsonProfiles
            {
                Status = 200,
                Queried = DateTime.Now.Ticks,
                Profiles = profileUpdates
            };

            return this.Json(jsonStatus);
        }

        [RequiresAuthentication()]
        public virtual ActionResult Update()
        {
            using (InOutDataContext db =
                new InOutDataContext(Settings.Default.dbConn))
            {
                MembershipUser user = dotNetMembership.GetUser();
                Profile profile = db.Profiles.Single(p => p.UserId == (Guid)user.ProviderUserKey);

                string inStatus = Request.Form["InStatus"];
                bool areIn = false;

                if (inStatus == "In")
                    areIn = true;

                if (!Request.Form.AllKeys.Contains<string>("OfficeStatus") && areIn != profile.InStatus)
                {
                    profile.InStatus = areIn;
                    profile.DateTimeLastUpdated = DateTime.Now;

                    db.SubmitChanges();
                } else
                {

                    string officeStatus = Request.Form["OfficeStatus"];

                    bool inOffice = false;

                    if (officeStatus == "Office")
                        inOffice = true;

                    profile.InStatus = areIn;
                    profile.OfficeStatus = inOffice;
                    profile.DateTimeLastUpdated = DateTime.Now;
                    profile.TicksLastUpdated = DateTime.Now.Ticks;

                    db.SubmitChanges();
                }

                return RedirectToAction("Index", "Updates");
            }
        }
    }
}
